﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace HostDetector
{
    public partial class HostForm : Form
    {

        HostFinder hf;
        private delegate void EventCallBack();
        string host;
        string name;
        long ping;
        EventCallBack hostdel;
        EventCallBack pingdel;

        BindingList<Player> visiblePlayers = new BindingList<Player>();

        public HostForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = true;
            hf = new HostFinder();
            hf.HostIPFoundEvent +=new HostFinder.HostHandler(hf_HostFoundEvent);
            hf.HostNameFoundEvent += new HostFinder.HostHandler(hf_HostNameFoundEvent);
            hf.PingEvent += new HostFinder.PingHandler(hf_PingEvent);
            hostdel = new EventCallBack(updateHost);
            pingdel = new EventCallBack(updatePing);
            hostTB.Text = "";
            pingLabel.Text = "";
            playerDGV.DataSource = visiblePlayers;


        }

        void hf_HostNameFoundEvent(string name)
        {
            this.name = name;
            this.BeginInvoke(hostdel);
        }



        void hf_PingEvent(long ping)
        {
            this.ping = ping;
            this.BeginInvoke(pingdel);
        }

        void hf_HostFoundEvent(string host)
        {
            this.host = host;
            this.BeginInvoke(hostdel);

        }
        
        
        void updateHost()
        {
            hostTB.Text = host;
            nameTB.Text = name;
            visiblePlayers.Clear();
            foreach(Player p in hf.CurrentPlayers)
                if(p != null)
                    visiblePlayers.Add(p);

            
        }

        void updatePing()
        {
            pingLabel.Text = ping.ToString();
        }





        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);//lazy, but effective
        }



    }
}
